package com.example.demo.jdbc;

import org.h2.Driver;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

/**
 * @author Rocket
 * @version 10.0.1
 * @date 2021-08-15 2:07 PM
 */
@WebServlet(name="Jdbc test", urlPatterns = {"/jdbc"})
public class JDBCTest extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Connection conn = null;
        try {
            Class.forName("org.h2.Driver");
            conn = DriverManager.getConnection("jdbc:h2:C:/study/db/h2/bin/test;AUTO_SERVER=TRUE;AUTO_RECONNECT=TRUE", "sa", "123");
            resp.getWriter().println(conn);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select * from test");
            resp.getWriter().println("id, name, birthday, my blob");
            while(rs.next()) {
                resp.getWriter().println(String.format("%d, %s, %s, null",
                        rs.getInt("id"),
                        rs.getString("name"),
                        rs.getDate("birthday")));
            }


        } catch (ClassNotFoundException | SQLException e) {
            return;
        } finally {
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                }
            }
        }


    }
}
